package com.chao.wind3j.base.config.commonConfig.xssConfig;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.text.StringEscapeUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "xssFilter", urlPatterns = "/*", asyncSupported = true)
public class XssFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        filterChain.doFilter(new HttpServletRequestWrapper(request) {
            @Override
            public String getQueryString() {
                return StringEscapeUtils.escapeHtml4(super.getQueryString());
            }

            @Override
            public String getParameter(String name) {
                return StringEscapeUtils.escapeHtml4(super.getParameter(name));
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (ArrayUtils.isEmpty(values)) {
                    return values;
                }
                int length = values.length;
                String[] escapeValues = new String[length];
                for (int i = 0; i < length; i++) {
                    escapeValues[i] = StringEscapeUtils.escapeHtml4(values[i]);
                }
                return escapeValues;
            }
        }, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
